package com.michael.retail.auth.entity;

import cn.hutool.core.collection.CollUtil;
import com.michael.retail.sys.api.pojo.entity.SysUser;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * 登录用户信息
 *
 * @author Michael
 */
@SuppressWarnings("AlibabaClassNamingShouldBeCamel")
@Data
@NoArgsConstructor
public class OAuth2UserDetails implements UserDetails {

    private static final long serialVersionUID = 1L;

    private Long id;

    private String username;

    private String password;

    private Boolean enabled;

    private String clientId;

    private Set<SimpleGrantedAuthority> authorities;

    /** 系统用户转 OAuth2UserDetails */
    public OAuth2UserDetails(SysUser user) {
        this.setId(user.getId());
        this.setUsername(user.getUsername());
        this.setPassword(user.getPassword());
        this.setEnabled(user.isEnable());

        List<String> authList = user.getAuthorities();
        if (CollUtil.isNotEmpty(authList)) {
            this.authorities = new HashSet<>();
            authList.forEach(auth -> this.authorities.add(new SimpleGrantedAuthority(auth)));
        }
    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
